//
//  Video.m
//  TowerDefence
//
//  Created by  on 5/21/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "Video.h"

@implementation Video

-(id)initVideoPlayer {
    self = [super init];
    return self;
}

-(void)loadVideoWith:(NSString *)_fileName ofType:(NSString *)_fileType {
    //create video file url
    NSURL *videoFilePath = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:_fileName ofType:_fileType]];
    //create moviePlayerControll object
    videoPlayer = [[MPMoviePlayerController alloc]initWithContentURL:videoFilePath];
    
    //register recive notification when the movie has finish playing
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:videoPlayer];
    
    if([videoPlayer respondsToSelector:@selector(setFullscreen:animated:)]) {
        videoPlayer.controlStyle = MPMovieControlStyleNone;
        videoPlayer.shouldAutoplay = YES;
        
        CGSize winSize = [[CCDirector sharedDirector] winSize];
		videoPlayer.view.frame = CGRectMake(45, 50, winSize.width-90, winSize.height-100);
		[[[CCDirector sharedDirector] openGLView] addSubview:videoPlayer.view];
    } else {
        [videoPlayer setMovieControlMode: MPMovieControlModeHidden];
		[self play];
    }
}

-(void)moviePlayBackDidFinish:(NSNotification*)notification {
    //if playback is finished, stop movie
    [self stop];
}

-(void)play {
    //if it is not playing, play it
    MPMoviePlaybackState playbackState = videoPlayer.playbackState;
    if(playbackState != MPMoviePlaybackStatePlaying) {
        [videoPlayer play];
    } else {
        NSLog(@"video is playing");
    }
}

-(void)pause {
    MPMoviePlaybackState playbackState = videoPlayer.playbackState;
    if(playbackState != MPMoviePlaybackStatePaused) {
        [videoPlayer pause];
    } else {
        NSLog(@"video is pausing");
    }
}

-(void)stop {
    MPMoviePlaybackState playbackState = videoPlayer.playbackState;
    if(playbackState != MPMoviePlaybackStateStopped) {
        [videoPlayer stop];
        
        [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:videoPlayer];
        
        //If the moviePlayer.view was added to the openGL view, it needs to be removed.
        if ([videoPlayer respondsToSelector:@selector(setFullscreen:animated:)]) {
            [videoPlayer.view removeFromSuperview];
        }
    } else {
        NSLog(@"video is stopping");
    }
}

@end
